using System;
using System.Collections;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Text;

namespace FreeFlow.Administration
{
	/// <summary>
	/// Collection of alerts for a user or a folder.
	/// </summary>
	public sealed class AlertCollection : DatabaseAware, IEnumerable, IEnumerable<Alert>, IList, IBindingList
	{
    private string userName;
    private string folderId;
    private AlertType alertType;
    /// <summary>
    /// Initializes a new instance of the <see cref="AlertCollection"/> class for the specified user.
    /// </summary>
    /// <param name="server">The server.</param>
    /// <param name="user">The user.</param>
    /// <param name="alertType">Type of the alerts to retrieve.</param>
    public AlertCollection(Server server, User user, AlertType alertType) : base(server)
    {
      this.userName = user.Name;
      this.alertType = alertType;
    }

    /// <summary>
    /// Initializes a new instance of the <see cref="AlertCollection"/> class for specified folder.
    /// </summary>
    /// <param name="server">The server.</param>
    /// <param name="folderId">The folder id.</param>
    /// <param name="alertType">Type of the alert.</param>
    public AlertCollection(Server server, string folderId, AlertType alertType) : base(server)
    {
      this.folderId = folderId;
      this.alertType = alertType;
    }

    private List<Alert> alerts;
    private void ReadAlerts()
    {
      if (alerts == null)
      {
        alerts = new List<Alert>();
        string sql;
        if (userName != null)
          sql = string.Format("SELECT * FROM eAlert WHERE eUserName = '{0}' AND eAlertType = '{1}' ORDER BY eAlertTime DESC", 
            SqlEscape(userName), AlertHelper.AlertTypeString(alertType));
        else
          sql = string.Format("SELECT * FROM eAlert WHERE eFolderID = '{0}' AND eAlertType = '{1}' ORDER BY eUserName", 
            folderId, AlertHelper.AlertTypeString(alertType));

        using (IDataReader reader = Server.ExecuteReader(sql))
        {
          while (reader.Read()) 
          {
            Alert alert = new Alert(Server, reader);
            alerts.Add(alert);
          }
        }
      }
    }

    /// <summary>
    /// Gets the <see cref="Alert"/> at the specified index.
    /// </summary>
    public Alert this[int index]
    {
      get
      {
        ReadAlerts();
        return (Alert)alerts[index];
      }
    }

    /// <summary>
    /// Determines whether this alert collection contains an alert for the specified user.
    /// </summary>
    /// <param name="userName">Name of the user.</param>
    /// <returns>
    /// 	<c>true</c> if this alert collection contains an alert for the specified user; otherwise, <c>false</c>.
    /// </returns>
    public bool ContainsUser(string userName)
    {
      for (int i = 0; i < Count; i++)
      {
        if (((Alert)alerts[i]).UserName == userName)
          return true;
      }
      return false;
    }

    /// <summary>
    /// Returns a <see cref="T:System.String"/> that is a list of the users contained in the collection.
    /// </summary>
    /// <returns>
    /// A <see cref="T:System.String"/> that is a list of the users contained in the collection.
    /// </returns>
    public override string ToString()
    {
      StringBuilder builder = new StringBuilder();
      for (int i = 0; i < Count; i++)
      {
        if (i > 0)
          builder.Append(", ");
        builder.Append(((Alert)alerts[i]).UserName);
      }
      return builder.ToString();
    }

    #region IEnumerable Members

    IEnumerator IEnumerable.GetEnumerator()
    {
      ReadAlerts();
      return alerts.GetEnumerator();
    }

    #endregion
    #region IEnumerable<Alert> Members

    /// <summary>
    /// Returns an enumerator that iterates through the collection.
    /// </summary>
    /// <returns>
    /// A <see cref="T:System.Collections.Generic.IEnumerator`1"/> that can be used to iterate through the collection.
    /// </returns>
    public IEnumerator<Alert> GetEnumerator()
    {
      ReadAlerts();
      return alerts.GetEnumerator();
    }

    #endregion
    #region IList Members

    /// <summary>
    /// Gets a value indicating whether the <see cref="T:System.Collections.IList"/> is read-only.
    /// </summary>
    public bool IsReadOnly
    {
      get
      {
        return true;
      }
    }

    object IList.this[int index]
    {
      get
      {
        ReadAlerts();
        return alerts[index];
      }
      set
      {
        throw new NotSupportedException(readOnlyListMessage);
      }
    }

    void IList.RemoveAt(int index)
    {
      throw new NotSupportedException(readOnlyListMessage);
    }

    void IList.Insert(int index, object value)
    {
      throw new NotSupportedException(readOnlyListMessage);
    }

    void IList.Remove(object value)
    {
      Remove((Alert)value);
    }

    /// <summary>
    /// Removes the specified alert from the collection and the database.
    /// </summary>
    /// <param name="alert">The alert to remove.</param>
    public void Remove(Alert alert)
    {
      alert.Delete();
      alerts.Remove(alert);
    }

    /// <summary>
    /// Determines whether the <see cref="T:System.Collections.IList"/> contains a specific value.
    /// </summary>
    /// <param name="value">The <see cref="T:System.Object"/> to locate in the <see cref="T:System.Collections.IList"/>.</param>
    /// <returns>
    /// 	<see langword="true"/> if the <see cref="T:System.Object"/>
    /// is found in the <see cref="T:System.Collections.IList"/>; otherwise, <see langword="false"/>.
    /// </returns>
    public bool Contains(object value)
    {
      ReadAlerts();
      return alerts.Contains((Alert)value);
    }

    void IList.Clear()
    {
      throw new NotSupportedException(readOnlyListMessage);
    }

    /// <summary>
    /// Determines the index of a
    /// specific item in the <see cref="T:System.Collections.IList"/>.
    /// </summary>
    /// <param name="value">The <see cref="T:System.Object"/> to locate in the <see cref="T:System.Collections.IList"/>.</param>
    /// <returns>
    /// The index of <paramref name="value"/> if found in the list; otherwise, -1.
    /// </returns>
    public int IndexOf(object value)
    {
      ReadAlerts();
      return alerts.IndexOf((Alert)value);
    }

    int IList.Add(object value)
    {
      Alert alert = (Alert)value;
      Add(alert);
      return IndexOf(alert);
    }

    private string DateTimeToSqlString(DateTime date)
    {
      if (Server.DatabaseType == DatabaseType.Oracle)
        return string.Format("to_date('{0}', 'YYYYMMDDHH24MISS')", date.ToString("yyyyMMddHHmmss"));
      else
        return string.Format("'{0}'", date.ToString("s"));
    }

    /// <summary>
    /// Adds the specified alert to the collection and the database.
    /// </summary>
    /// <param name="alert">The alert to add.</param>
    public void Add(Alert alert)
    {
      using (IDbTransaction transaction = Server.BeginTransaction())
      {
        Server.ExecuteNonQuery(transaction, string.Format("DELETE FROM eAlert WHERE eUserName = '{0}' AND eFolderID = '{1}'",
          SqlEscape(alert.UserName), alert.FolderId));
        Server.ExecuteNonQuery(transaction, string.Format("INSERT INTO eAlert (eUserName, eFolderID, eMapName, eStageName, eFolderName, eEngineName, " +
          "eCategory, ePriority, eAlertNr, eAlertTime, eDeadline, eUpdated, eAlertType, eSubject, eAlertMessage) " +
          "VALUES ('{0}', '{1}', '{2}', '{3}', '{4}', '{5}', '{6}', {7}, {8}, {9}, {10}, {11}, '{12}', '{13}', '{14}')",
          SqlEscape(alert.UserName), alert.FolderId, SqlEscape(alert.MapName),
          SqlEscape(alert.StageName), SqlEscape(alert.FolderName), SqlEscape(alert.EngineName), SqlEscape(alert.Category),
          alert.Priority, alert.AlertNumber, DateTimeToSqlString(alert.Updated), DateTimeToSqlString(alert.Deadline),
          DateTimeToSqlString(alert.Updated), AlertHelper.AlertTypeString(alertType), SqlEscape(alert.Subject), SqlEscape(alert.Message)));

        transaction.Commit();
      }
      alerts.Add(alert);
    }

    /// <summary>
    /// Adds a new alert for the specified folder and user.
    /// </summary>
    /// <param name="folder">The folder.</param>
    /// <param name="userName">Name of the user who will get the alert.</param>
    /// <returns>The index where the alert has been added.</returns>
    public int Add(Folder folder, string userName)
    {
      Alert alert = new Alert(Server, folder, userName);
      Add(alert);
      return IndexOf(alert);
    }

    /// <summary>
    /// Gets a value indicating whether the <see cref="T:System.Collections.IList"/> has a fixed size.
    /// </summary>
    public bool IsFixedSize
    {
      get
      {
        return true;
      }
    }

    #endregion
    #region ICollection Members

    /// <summary>
    /// Gets a value
    /// indicating whether access to the <see cref="T:System.Collections.ICollection"/> is synchronized
    /// (thread-safe).
    /// </summary>
    public bool IsSynchronized
    {
      get
      {
        return false;
      }
    }

    /// <summary>
    /// Gets the number of alerts contained in the collection.
    /// </summary>
    public int Count
    {
      get
      {
        ReadAlerts();
        return alerts.Count;
      }
    }

    /// <summary>
    /// Copies the elements of
    /// the <see cref="T:System.Collections.ICollection"/> to an <see cref="T:System.Array"/>, starting at a particular <see cref="T:System.Array"/> index.
    /// </summary>
    /// <param name="array">The one-dimensional <see cref="T:System.Array"/> that is the destination of the elements copied from <see cref="T:System.Collections.ICollection"/>. The <see cref="T:System.Array"/> must have zero-based indexing.</param>
    /// <param name="index">The zero-based index in <paramref name="array"/> at which copying begins.</param>
    /// <exception cref="T:System.ArgumentNullException">
    /// 	<paramref name="array"/> is <see langword="null"/>.</exception>
    /// <exception cref="T:System.ArgumentOutOfRangeException">
    /// 	<paramref name="index"/> is less than zero.</exception>
    /// <exception cref="T:System.ArgumentException">
    /// 	<para>
    /// 		<paramref name="array"/> is multidimensional.</para>
    /// 	<para>-or-</para>
    /// 	<para>
    /// 		<paramref name="index"/> is equal to or greater than the length of <paramref name="array"/>.</para>
    /// 	<para>-or-</para>
    /// 	<para>The number of elements in the source <see cref="T:System.Collections.ICollection"/> is greater than the available space from <paramref name="index"/> to the end of the destination <paramref name="array"/>.</para>
    /// </exception>
    /// <exception cref="T:System.InvalidCastException">The type of the source <see cref="T:System.Collections.ICollection"/> cannot be cast automatically to the type of the destination <paramref name="array"/>.</exception>
    public void CopyTo(Alert[] array, int index)
    {
      ReadAlerts();
      alerts.CopyTo(array, index);
    }

    void ICollection.CopyTo(Array array, int index)
    {
      CopyTo((Alert[])array, index);
    }

    /// <summary>
    /// Gets an object that
    /// can be used to synchronize access to the <see cref="T:System.Collections.ICollection"/>.
    /// </summary>
    public object SyncRoot
    {
      get
      {
        return null;
      }
    }

    #endregion
    #region IBindingList Members

    void IBindingList.ApplySort(PropertyDescriptor property, ListSortDirection direction)
    {
      ReadAlerts();
      sortProperty = property;
      sortDirection = direction;
      alerts.Sort(new Comparer<Alert>(sortProperty, sortDirection));
    }

    private PropertyDescriptor sortProperty;
    PropertyDescriptor IBindingList.SortProperty
    {
      get
      {
        return sortProperty;
      }
    }

    bool IBindingList.SupportsSorting
    {
      get
      {
        return true;
      }
    }

    bool IBindingList.IsSorted
    {
      get
      {
        return (sortProperty != null);
      }
    }

    void IBindingList.RemoveSort()
    {
      sortProperty = null;
    }

    private ListSortDirection sortDirection;
    ListSortDirection IBindingList.SortDirection
    {
      get
      {
        return sortDirection;
      }
    }

    #region not implemented 
    int IBindingList.Find(PropertyDescriptor property, object key)
    {
      return 0;
    }

    bool IBindingList.AllowRemove
    {
      get
      {
        return false;
      }
    }

    bool IBindingList.SupportsSearching
    {
      get
      {
        return false;
      }
    }

    private ListChangedEventHandler listChanged;
    event ListChangedEventHandler IBindingList.ListChanged
    {
      add { listChanged += value; }
      remove { listChanged -= value; }

    }

    bool IBindingList.SupportsChangeNotification
    {
      get
      {
        return false;
      }
    }

    object IBindingList.AddNew()
    {
      return null;
    }

    bool IBindingList.AllowEdit
    {
      get
      {
        return false;
      }
    }

    void IBindingList.RemoveIndex(PropertyDescriptor property)
    {
    }

    void IBindingList.AddIndex(PropertyDescriptor property)
    {
    }

    bool IBindingList.AllowNew
    {
      get
      {
        return false;
      }
    }

    #endregion
    #endregion
  }
}
